package com.li.springbootproject.config.thread;

import com.alibaba.fastjson.JSON;
import com.lidong.toolkit.constant.LogConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author LiDong
 * @version 1.0.0
 * @className ThreadConfig.java
 * @createTime 2021年06月05日 21:10:00
 */
@Configuration
@EnableAsync
public class ThreadPoolConfig {

    private static final Logger logger = LoggerFactory.getLogger(ThreadPoolConfig.class);

    @Bean
    public Executor globalExecutor() {
        // 获取当前cpu核数
        int cpuNum = Runtime.getRuntime().availableProcessors();
        ThreadPoolTaskExecutor poolExecutor = new ThreadPoolTaskExecutor();
        poolExecutor.setCorePoolSize(cpuNum);
        //配置最大线程数
        poolExecutor.setMaxPoolSize(cpuNum * 2);
        //配置队列大小
        poolExecutor.setQueueCapacity(300);
        //线程存活时间
        poolExecutor.setKeepAliveSeconds(60);
        //配置线程池中的线程的名称前缀
        poolExecutor.setThreadNamePrefix("globalExecutor");
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        poolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        poolExecutor.initialize();
        logger.info(LogConst.FLAG);
        logger.info(LogConst.LOG_SUCCESS_PREFIX + "Spring 全局线程池初始化完成......");
        logger.info(JSON.toJSONString(poolExecutor));
        logger.info(LogConst.FLAG);
        return poolExecutor;
    }
}
